<template>
  <!-- 工单表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1500"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="产品" prop="materialCode">
            <el-input
              v-model="formData.materialCode"
              placeholder="请输入产品"
              clearable
              readonly
              @click="showWorkOrderSelect"
              style="width: 220px"
            >
              <template #append>
                <el-button @click="resetMaterial">清除</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="5">
          <el-form-item label="日期" prop="requireDate">
            <el-date-picker
              v-model="formData.requireDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="">
            <el-button
              type="primary"
              @click="getPlanWorkingForm"
              :loading="selectLoading"
              >查询</el-button
            >
            <!--<el-button @click="resetForm">重置</el-button>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item label="熔炼设备" prop="equipInfoId">
            <el-select
              v-model="existEquipInfoIdList"
              placeholder="请选择熔炼设备"
              style="width: 220px"
              @change="changeExistEquipInfo"
              filterable
              multiple
              :multiple-limit="2"
              collapse-tags
              :max-collapse-tags="1"
              clearable
            >
              <el-option
                v-for="item in equipInfoList"
                :key="item.id"
                :label="`${item.equipCode}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="班制" prop="shiftSystemId">
            <el-select
              v-model="formData.shiftSystemId"
              placeholder="请选择班制"
              @change="changeShiftSet"
              style="width: 220px"
            >
              <el-option
                v-for="item in shiftSetList"
                :key="item.id"
                :label="item.shiftSetName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="冷起班次" prop="shiftIdHead">
            <el-select
              v-model="formData.shiftIdHead"
              placeholder="请选择班制"
              clearable
              style="width: 220px"
            >
              <el-option
                v-for="item in shiftList"
                :key="item.id"
                :label="item.shiftCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="留线班次" prop="shiftIdTail">
            <el-select
              v-model="formData.shiftIdTail"
              placeholder="请选择班制"
              style="width: 220px"
              clearable
            >
              <el-option
                v-for="item in shiftList"
                :key="item.id"
                :label="item.shiftCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="70px">
            <el-button type="primary" @click="smartSort">智能排序</el-button>
            <el-button type="primary" @click="ascSort">排序</el-button>
            <!--<el-button @click="resetForm">重置</el-button>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="班次" prop="shiftId">
            <el-select
              v-model="formData.shiftId"
              placeholder="请输入班次"
              clearable
              style="width: 220px"
            >
              <el-option
                v-for="item in shiftList"
                :key="item.id"
                :label="item.shiftCode"
                :value="item.shiftId"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="sketch_content">
          <el-table
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <!--<el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />-->
            <el-table-column
              label="顺序号"
              props="workSequence"
              min-width="150"
              show-overflow-tooltip
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.workSequence'"
                  :rules="rules.workSequence"
                  label-width="0"
                >
                  <el-input-number
                    v-model="row.workSequence"
                    placeholder="请输入顺序号"
                    :min="1"
                    :max="formData.details.length"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="产品名称"
              props="materialName"
              min-width="150"
            >
              <template #default="{ row }">
                {{ row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="炉号"
              props="stoveNum"
              min-width="150"
              show-overflow-tooltip
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.stoveNum'"
                  :rules="rules.stoveNum"
                  label-width="0"
                >
                  <el-select
                    v-model="row.stoveNum"
                    placeholder="请选择炉号"
                    clearable
                    style="width: 100%"
                    @change="changeEquipInfo($index, row.stoveNum)"
                  >
                    <el-option
                      v-for="item in existEquipInfoList"
                      :key="item.id"
                      :label="item.equipCode"
                      :value="item.equipCode"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="班次"
              props="shiftId"
              min-width="150"
              align="center"
              style="padding-top: 15px"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.shiftId'"
                  :rules="rules.sonshiftId"
                  label-width="0"
                >
                  <el-select
                    v-model="row.shiftId"
                    placeholder="请输入班次"
                    clearable
                    style="width: 100%"
                    @change="changeShift($index, row.shiftId)"
                  >
                    <el-option
                      v-for="item in shiftList"
                      :key="item.id"
                      :label="item.shiftCode"
                      :value="item.shiftId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="冷起"
              prop="isHead"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <span v-if="row.isHead == 1">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column
              label="留线"
              prop="isTail"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="center"
            >
              <template #default="{ row }">
                <span v-if="row.isTail == 1">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              prop="amount"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="模数"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="计划包数"
              prop="planPackage"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="计划炉数"
              prop="planStove"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <!--<el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="120"
            >
              <template #default="scope">
                <el-button
                  :disabled="scope.$index == 0"
                  type="primary"
                  link
                  @click.stop="moveUp(scope.$index)"
                >
                  上移
                </el-button>
                <el-button
                  :disabled="scope.$index == formData.details.length - 1"
                  type="primary"
                  link
                  @click.stop="shiftDown(scope.$index)"
                >
                  下移
                </el-button>
              </template>
            </el-table-column>-->
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="formData.details.length > 0"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="formData.plantId"
      :brekList="brekList"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "GENERATIONDAYPLAN",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const validateSerial = (rule, value) => {
  const filter = formData.details.filter((item) => item.workSequence === value);
  if (filter.length > 1) {
    return Promise.reject("序号已存在");
  }
  return Promise.resolve();
};
const rules = reactive({
  // materialCode: [{ required: true, message: "请输入产品", trigger: "change" }],
  // requireDate: [{ required: true, message: "请选择日期", trigger: "change" }],
  sonshiftId: [{ required: true, message: "请选择班次", trigger: "change" }],
  shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
  stoveNum: [{ required: true, message: "请选择炉号", trigger: "change" }],
  equipInfoId: [{ required: true, message: "请选择设备", trigger: "change" }],
  workSequence: [
    { required: true, message: "请输入序号", trigger: "change" },
    {
      validator: validateSerial,
      trigger: ["blur", "change"],
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  producePlanCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  workSequence: "",
  planNum: "",
  requireDate: getCurrentDate(),
  planQuantity: "",
  planStatus: "",
  productionVersionNumber: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  shiftSystemId: "",
  status: 0,
  details: [],
  equipInfoId: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        requireDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        requireDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.clearValidate();
  formRef.value.resetFields();
  formData.id = "";
  formData.producePlanCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.workSequence = "";
  formData.planNum = "";
  formData.requireDate = getCurrentDate();
  formData.planQuantity = "";
  formData.planStatus = "";
  formData.productionVersionNumber = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.details = [];
  shiftList.value = [];
  details.value = {};
  existEquipInfoList.value = [];
  existEquipInfoIdList.value = [];
}
const loading = ref(false);
const selectLoading = ref(false);

/** 工单表保存提交 */
async function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      let arr = JSON.parse(JSON.stringify(formData.details));
      arr = arr.sort((a, b) => a.workSequence - b.workSequence);
      //数组转map
      let shiftMap = shiftList.value.reduce((acc, cur) => {
        acc[cur.shiftId] = cur.sequenceCode;
        return acc;
      }, {});
      arr[0].sequenceCode = shiftMap[arr[0].shiftId];
      for (let i = 1; i < arr.length; i++) {
        arr[i].sequenceCode = shiftMap[arr[i].shiftId];
        if (arr[i].sequenceCode < arr[i - 1].sequenceCode) {
          ElMessage.error(`班次顺序错误，请点击排序按钮重新排序！`);
          return;
        }
      }
      console.log("arr", arr);
      loading.value = true;
      await request({
        url: "/mes/mesplanmonthplanactual/saveBatchDayPlanNew",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`保存成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  // getShiftSetList();
  getEquipInfoListList();
});
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  formData.materialId = "";
  formData.materialCode = "";
};

// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
//设备
const equipInfoList = ref([]);
async function getEquipInfoListList() {
  await request({
    url: "mdm/mdmequipInfo/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1, equipTypeCode: "焦炉" },
  }).then((res) => {
    equipInfoList.value = res.data;
  });
}
const existEquipInfoIdList = ref([]);
const existEquipInfoList = ref([]);
const changeExistEquipInfo = () => {
  formData.equipInfoId = existEquipInfoIdList.value.join(",");
  existEquipInfoList.value = existEquipInfoIdList.value
    .map((id) => equipInfoList.value.find((item) => item.id === id))
    .filter((item) => item !== undefined);
};
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    shiftSetList.value = res.data;
    getProcessesList();
  });
}
async function getProcessesList() {
  await request({
    url: "/mes/mesprocess/getList",
    method: "post",
    data: {
      plantId: formData.plantId,
      processType: 3,
      enabled: 1,
    },
  }).then((res) => {
    if (res.data.length > 0 && res.data[0]?.mesShiftSetId)
      changeShiftSet(res.data[0].mesShiftSetId);
  });
}
function changeShiftSet(val) {
  formData.shiftSystemId = val;
  shiftList.value = [];
  formData.shiftIdHead = "";
  formData.shiftIdTail = "";
  if (val) {
    getShifts();
    if (formData.details.length > 0) {
      formData.details.forEach((item) => {
        item.shiftSystemId = val;
      });
    }
  }
}

//班次
const shiftList = ref([]);
async function getShifts() {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: formData.shiftSystemId,
    },
  }).then((res) => {
    shiftList.value = res.data;
    formData.details.forEach((item, index) => {
      item.shiftId = shiftList.value[0].shiftId;
      item.shiftCode = shiftList.value[0].shiftCode;
      item.sequenceCode = shiftList.value[0].sequenceCode;
    });
  });
}
//获取查询条件下的工单列表
const details = ref();
async function getPlanWorkingForm() {
  if (!formData.requireDate) {
    ElMessage.error(`请选择日期`);
    return;
  }
  selectLoading.value = true;
  await request({
    url: "/mes/mesrestperiod/getRestDay",
    method: "post",
    data: formData.requireDate,
  })
    .then((res: any) => {
      if (res.code != 200) {
        selectLoading.value = false;
        return;
      }
    })
    .finally(() => {
      selectLoading.value = false;
    });
  await request({
    url: "/mes/mesplanmonthplanactual/getPlanList",
    method: "post",
    data: formData,
  })
    .then((res: any) => {
      if (res.code == 200) {
        res.data.forEach((item, index) => {
          item.workSequence = index + 1;
        });
        formData.details = res.data;
        if (formData.details.length > 0) {
          formData.plantId = res.data[0].plantId;
          getShiftSetList();
        }
      }
    })
    .finally(() => {
      selectLoading.value = false;
    });
}
//智能排序
async function smartSort() {
  if (formData.details.length == 0) {
    ElMessage.error(`请选择获取数据`);
    return;
  }
  if (existEquipInfoIdList.value.length == 0) {
    ElMessage.error(`请选择设备`);
    return;
  }
  if (!formData.shiftSystemId) {
    ElMessage.error(`请选择班制`);
    return;
  }
  await request({
    url: "/mes/mesplanmonthplanactual/sortBatchDayPlan",
    method: "post",
    data: {
      list: formData.details,
      shiftSetDTO: shiftSetList.value.find(
        (item) => item.id == formData.shiftSystemId
      ),
      mesShiftHead: shiftList.value.find(
        (item) => item.id == formData.shiftIdHead
      ),
      mesShiftTail: shiftList.value.find(
        (item) => item.id == formData.shiftIdHead
      ),
      listEquip: existEquipInfoList.value,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      formData.details = res.data;
    }
  });
}
const moveUp = (index: number) => {
  const temp = formData.details[index];
  formData.details.splice(index, 1);
  formData.details.splice(index - 1, 0, temp);
};
const shiftDown = (index: number) => {
  const temp = formData.details[index];
  formData.details.splice(index, 1);
  formData.details.splice(index + 1, 0, temp);
};
function changeEquipInfo(index: number, code: any) {
  if (code) {
    existEquipInfoList.value.forEach((item: any) => {
      if (item.equipCode == code) {
        formData.details[index].deviceId = item.id;
        formData.details[index].stoveNum = item.equipCode;
        formData.details[index].deviceName = item.equipName;
      }
    });
  } else {
    formData.details[index].deviceId = "";
    formData.details[index].stoveNum = "";
    formData.details[index].deviceName = "";
  }
}
//升序排列
async function ascSort() {
  // formData.details.sort((a, b) => a.workSequence - b.workSequence);
  // formRef.value.validate();
  if (formData.details.length == 0) {
    ElMessage.error(`请选择获取数据`);
    return;
  }
  if (existEquipInfoIdList.value.length == 0) {
    ElMessage.error(`请选择设备`);
    return;
  }
  if (!formData.shiftSystemId) {
    ElMessage.error(`请选择班制`);
    return;
  }
  await request({
    url: "/mes/mesplanmonthplanactual/sortBatch",
    method: "post",
    data: {
      list: formData.details,
      shiftSetDTO: shiftSetList.value.find(
        (item) => item.id == formData.shiftSystemId
      ),
      listEquip: existEquipInfoList.value,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      formData.details = res.data;
      formRef.value.clearValidate();
    }
  });
}
//班次
function changeShift(index: number, id: string) {
  shiftList.value.forEach((item: any) => {
    if (item.shiftId == id) {
      formData.details[index].shiftCode = item.shiftCode;
      formData.details[index].sequenceCode = item.sequenceCode;
    }
  });
}
</script>
<style lang="scss" scoped>
.sketch_content {
  // 必须有高度 overflow 为自动
  overflow: auto;
  height: 500px;
}

// 滚动条的样式,宽高分别对应横竖滚动条的尺寸
.sketch_content::-webkit-scrollbar {
  width: 3px;
}

// 滚动条里面默认的小方块,自定义样式
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798af;
  border-radius: 2px;
}

// 滚动条里面的轨道
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
</style>
